package com.crm.api.config.security;

import com.crm.api.common.JwtUtil;
import com.crm.api.config.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取请求头中的JWT
        String authHeader = request.getHeader(jwtConfig.getHeader());

        if (StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) {
            // 截取JWT
            String jwt = authHeader.substring(7);

            // 从JWT中获取用户名
            String username = jwtUtil.getUsernameFromToken(jwt);

            // 如果可以获取到用户名且当前SecurityContext中没有认证信息
            if (StringUtils.hasText(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 加载用户信息
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                // 验证JWT是否有效
                if (jwtUtil.validateToken(jwt, userDetails)) {
                    // 创建认证信息
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());

                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    // 设置到SecurityContext中
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                    log.debug("用户[{}]认证成功", username);
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}